<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" placeholder="input your content">
    <button>send request</button>
    <div></div>
    <div id="status"></div>
    <img id="pic">
    <script>
        var input = document.querySelector('input')
        var button = document.querySelector('button')
        var div = document.querySelector('div')
        var dv = document.querySelector('#status')


        var  url = "data:image/png;base64,"
        var image = document.getElementById('pic')
        // var key = JSON.stringify({38:"前进"})

        const TYPE_ENTER = 0
        const TYPE_LEAVE = 1
        const TYPE_MSG = 2

        // var socket = new WebSocket('ws://echo.websocket.org')
        var socket = new WebSocket('ws://localhost:3000')

        socket.addEventListener('open', function(){
            div.innerHTML = 'connected'
            dv.innerText = '无操作'
            dv.style.color = 'blue'
            // div.appendChild(dv)

        })

        button.addEventListener('click', function(){
            var value = input.value
            socket.send(value)
            input.value=''
        })

        socket.addEventListener('message', function(e){
            if(e.data === 'connected'){
                socket.send('web')
            }else{
                // console.log(e.data)
                // div.innerHTML = e.data

                var data = JSON.parse(e.data)
                if (data.type === 3){
                    image.src=url+data.msg
                }else{
                    if (data.msg === "38") {
                        dv.innerText = '前进'
                    }else if (data.msg === "39") {
                        dv.innerText = '右移'
                    }else if (data.msg === "40") {
                        dv.innerText = '后退'
                    }else if (data.msg === "37") {
                        dv.innerText = '左移'
                    }else if (data.msg === "87") {
                        dv.innerText = '升高'
                    }else if (data.msg === "83") {
                        dv.innerText = '下降'
                    }else if (data.msg === "65") {
                        dv.innerText = '左转'
                    }else if (data.msg === "68") {
                        dv.innerText = '右转'
                    }
                }
            }

        })

        document.addEventListener('keydown', function(e) {
            console.log('down' + e.keyCode);
            socket.send(e.keyCode)
        })

        document.addEventListener('keyup', function(e) {
            console.log('up' + e.keyCode);
            socket.send(0)
        })

    </script>
</body>
</html>